package com.qst.servlet;

import com.alibaba.fastjson.JSON;
import com.qst.biz.RoleBiz;
import com.qst.biz.UserBiz;
import com.qst.biz.impl.RoleBizImpl;
import com.qst.biz.impl.UserBizImpl;
import com.qst.common.StateConstaint;
import com.qst.entity.Role;
import com.qst.entity.User;
import com.qst.utils.HttpResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(
        name = "UserLoginServlet",
        urlPatterns = "/api/user/login"
)
public class UserLoginServlet  extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("UTF-8");
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        String userName = req.getParameter("userName");
        String userPwd = req.getParameter("userPwd");
        User user=new User(userName,userPwd);

        UserBiz userBiz=new UserBizImpl();
        User loginUser = userBiz.login(user);
        //code msg data
        HttpResult<User> httpResult=new HttpResult<>();
        httpResult.setData(loginUser);
        if (loginUser!=null){
            httpResult.setCode(StateConstaint.DATA_OK);
            httpResult.setMsg("success");
            //根据用户获取角色
            RoleBiz roleBiz=new RoleBizImpl();
            Role loginUserRole = roleBiz.getRoleByUserID(loginUser.getUserID());
            System.out.println(loginUserRole);

        }else{
            httpResult.setCode(StateConstaint.DATA_NOT_FOUND);
            httpResult.setMsg("用户名或密码错误");
        }
        String content = JSON.toJSONString(httpResult);
        System.out.println(content);
        PrintWriter out = resp.getWriter();

        out.write(content);
        out.flush();
        out.close();


    }
}
